import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:nft_shop/box/model/models.dart';
import 'package:nft_shop/box/page/details/split_box_page.dart';
import 'package:nft_shop/login/controller/user_controller.dart';
import 'package:nft_shop/market/model/models.dart';
import 'package:nft_shop/my/model/models.dart';
import 'package:nft_shop/my/page/set/details_web_page.dart';
import 'package:nft_shop/net/dio_api.dart';
import 'package:nft_shop/net/service_repository.dart';
import 'package:nft_shop/res/global.dart';
import 'package:nft_shop/widgets/load_image.dart';
import 'package:nft_shop/widgets/my_app_bar.dart';
import 'package:nft_shop/widgets/my_button.dart';
import 'package:nft_shop/widgets/my_scroll_view.dart';
import 'package:tobias/tobias.dart' as tobias;
import 'package:fluwx/fluwx.dart' as fluwx;
import 'package:url_launcher/url_launcher.dart';

class BuyConfirmOrderPage extends StatefulWidget {
  GoodsInfo? goodsinfo;
  int type; //1盲盒 2藏品 3单个盲盒

  BuyConfirmOrderPage({Key? key, this.goodsinfo, required this.type})
      : super(key: key);

  @override
  _BuyConfirmOrderPageState createState() => _BuyConfirmOrderPageState();
}

class _BuyConfirmOrderPageState extends State<BuyConfirmOrderPage> {
  bool isCheck = false;
  int payType = 1;
  late GoodsMangModel mangModel;

  final TextEditingController _controller = TextEditingController();

  final FocusNode _nodeText = FocusNode();
  ConfigNameDetail? article;
  ConfigNameDetail? alArticle;
  StreamSubscription? testSubscription;

  @override
  void initState() {
    super.initState();
    getConfigNameDetailAli("alipay_is_open");
  }

  @override
  void dispose() {
    super.dispose();
    try {
      testSubscription?.cancel();
    } catch (e) {}
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: MyAppBar(
        centerTitle: "确认订单",
      ),
      body: MyScrollView(
        children: [
          storageView(),
          Container(
            height: 5,
            color: Global.kTheme.colorLine,
          ),
          goodsView(),
          Container(
            height: 5,
            color: Global.kTheme.colorLine,
          ),
          payView(),
          Container(
            height: 5,
            color: Global.kTheme.colorLine,
          ),
          instructionsView(),
        ],
        bottomButton: Container(
          height: 110,
          padding: EdgeInsets.symmetric(horizontal: 15, vertical: 15),
          decoration: BoxDecoration(
              border: Border(
            top: Divider.createBorderSide(context,
                color: Global.kTheme.colorLine, width: 1),
          )),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              InkWell(
                onTap: () {
                  setState(() {
                    isCheck = !isCheck;
                  });
                },
                child: Text.rich(
                  TextSpan(children: [
                    WidgetSpan(
                        child: Icon(
                      isCheck
                          ? Icons.check_box
                          : Icons.check_box_outline_blank_sharp,
                      size: 18,
                    )),
                    TextSpan(
                        text: "点击确认支付则视为同意",
                        style: TextStyle(
                          fontSize: 12,
                          color: Color(0xFFA0A0A0),
                        )),
                    WidgetSpan(
                        child: InkWell(
                      onTap: () {
                        Get.to(DetailsWebPage(
                          name: "数字资产交易服务条款",
                        ));
                      },
                      child: Text(
                        "《数字资产交易服务条款》",
                        style: TextStyle(
                          fontSize: 12,
                          color: Color(0xFF5F7EA3),
                        ),
                      ),
                    ))
                  ]),
                  textAlign: TextAlign.center,
                ),
              ),
              SizedBox(
                height: 14,
              ),
              Container(
                height: 40,
                decoration: BoxDecoration(
                  color: Global.kTheme.colorBackground3,
                  borderRadius: BorderRadius.circular(4),
                ),
                child: MyButton(
                  minHeight: 40,
                  onPressed: () async {
                    if (!isCheck) {
                      EasyLoading.showToast("请勾选协议");
                      return;
                    }
                    if ((alArticle?.value == "false" &&
                        article?.value == "false")|| payType==-1) {
                      EasyLoading.showToast("支付通道已关闭");
                      return;
                    }
                    EasyLoading.show(status: "加载中...");
                    if (widget.type == 1) {
                      //盲盒
                      await ServiceRepository.purchaseGoodsMang(
                              widget.goodsinfo!.info!.id!)
                          .then((value) async {
                        mangModel = value;
                        dynamic model;
                        try {
                          if (payType == 1) {
                            model = await ServiceRepository.goodsPay3(
                                id: mangModel.orderId ?? "");
                            toWebAipay(model);
                          } else {
                            dynamic data = ServiceRepository.goodsWXPay(
                                id: mangModel.orderId ?? "");
                            toWXPay(data);
                          }
                        } catch (e, s) {
                          EasyLoading.showToast(http.setError(e, s));
                        }
                      });
                    } else {
                      if (UserController.to.member.buyMuchStatus == "1" &&
                          widget.goodsinfo!.info!.allCount! > 1) {
                        if (_controller.text.length != 0) {
                          EasyLoading.showToast("请输入数量");
                          return;
                        }
                        if (int.parse(_controller.text) < 1) {
                          EasyLoading.showToast("数量不能为0");
                          return;
                        }

                        //批量购买
                        try {
                          await ServiceRepository.batchBuyCollection(
                                  specialId:
                                      widget.goodsinfo!.info!.id!.toString(),
                                  count: _controller.text)
                              .then((value) async {
                            mangModel = value;
                            dynamic model;
                            try {
                              if (payType == 1) {
                                model = await ServiceRepository.goodsPay3(
                                    id: mangModel.orderId ?? "");
                                toWebAipay(model);
                              } else {
                                dynamic data = ServiceRepository.goodsWXPay(
                                    id: mangModel.orderId ?? "");
                                toWXPay(data);
                              }
                            } catch (e, s) {
                              EasyLoading.showToast(http.setError(e, s));
                            }
                          });
                        } catch (e, s) {
                          EasyLoading.showToast(http.setError(e, s));
                        }
                      } else {
                        //单个购买
                        try {
                          await ServiceRepository.purchaseGoods(
                                  widget.goodsinfo!.info!.id!)
                              .then((value) async {
                            mangModel = value;

                            try {
                              if (payType == 1) {
                                dynamic model;
                                model = await ServiceRepository.goodsPay3(
                                    id: mangModel.orderId ?? "");
                                toWebAipay(model);
                              } else {
                                dynamic data =
                                    await ServiceRepository.goodsWXPay(
                                        id: mangModel.orderId ?? "");
                                toWXPay(data);
                              }
                            } catch (e, s) {
                              EasyLoading.showToast(http.setError(e, s));
                            }
                          });
                        } catch (e, s) {
                          EasyLoading.showToast(http.setError(e, s));
                        }
                      }
                    }
                  },
                  text: "确认支付",
                  fontSize: 16,
                  textColor: Colors.white,
                  backgroundColor: Global.kTheme.colorBackground3,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  //存储地址
  Widget storageView() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 15, vertical: 10),
      child: Column(
        children: [
          Row(
            children: [
              Text(
                "存储地址",
                style: TextStyle(
                    fontSize: 14,
                    color: Global.kTheme.textPrimary1,
                    fontFamily: Global.mySemiboldFont),
              ),
              Spacer(),
              Text(
                omitAddress(UserController.to.member.accountAddress ?? ""),
                style: TextStyle(
                    fontSize: 12,
                    color: Global.kTheme.textPrimary1,
                    fontFamily: Global.mySemiboldFont),
              ),
              InkWell(
                onTap: () {
                  ClipboardData data = new ClipboardData(
                      text: UserController.to.member.accountAddress ?? "");
                  Clipboard.setData(data);
                  EasyLoading.showToast("复制成功");
                },
                child: LoadAssetImage(
                  "my_copy",
                  width: 16,
                  height: 16,
                ),
              ),
            ],
          ),
          SizedBox(
            height: 10,
          ),
          Row(
            children: [
              Expanded(
                child: Container(
                  decoration: BoxDecoration(
                    color: Color(0xFFF8F8F8),
                    borderRadius: BorderRadius.circular(4),
                  ),
                  padding: EdgeInsets.all(8),
                  child: Text(
                    "该地址由平台生成,帮助您存储数字藏品,完成链上交易",
                    style: TextStyle(
                        fontSize: 12, color: Global.kTheme.inputHint1),
                  ),
                ),
              ),
            ],
          ),
          SizedBox(
            height: 8,
          ),
        ],
      ),
    );
  }

  //藏品信息
  Widget goodsView() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 15),
      child: Column(
        children: [
          Container(
            padding: EdgeInsets.only(top: 25, bottom: 15),
            child: Row(
              children: [
                ClipRRect(
                    borderRadius: BorderRadius.circular(4),
                    child: LoadImage(widget.goodsinfo!.info!.thumb ?? "",
                        fit: BoxFit.fitHeight,
                        width: 80,
                        height: 80,
                        holderImg: "my_holderImg")),
                SizedBox(
                  width: 10,
                ),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        widget.goodsinfo!.info!.title ?? "",
                        style: TextStyle(
                            fontSize: 14,
                            color: Global.kTheme.textPrimary4,
                            fontFamily: Global.mySemiboldFont),
                      ),
                      SizedBox(
                        height: 5,
                      ),
                      Text(
                        widget.goodsinfo!.info!.nickname ?? "",
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(
                            fontSize: 14,
                            color: Global.kTheme.inputHint1,
                            fontFamily: Global.mySemiboldFont),
                      ),
                      SizedBox(
                        height: 14,
                      ),
                      Text(
                        (widget.type == 1 || widget.type == 3)
                            ? "¥${widget.goodsinfo!.info!.basePrice ?? ""}"
                            : "¥${widget.goodsinfo!.info!.price ?? ""}",
                        style: TextStyle(
                            fontSize: 13,
                            color: Global.kTheme.textPrimary4,
                            fontFamily: Global.mySemiboldFont),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
          Visibility(
            visible: UserController.to.member.buyMuchStatus == "1" &&
                widget.goodsinfo!.info!.allCount! > 1 &&
                widget.type == 2,
            child: Container(
              height: 40,
              margin: EdgeInsets.only(bottom: 15),
              padding: EdgeInsets.symmetric(horizontal: 10),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(4),
                border: Border.all(color: Color(0xFFE0E0E0), width: 1),
              ),
              child: TextField(
                controller: _controller,
                focusNode: _nodeText,
                keyboardType: TextInputType.multiline,
                maxLines: 1,
                //不限制行数
                decoration: InputDecoration(
                  labelStyle: TextStyle(
                      fontSize: 14,
                      color: Global.kTheme.textPrimary12,
                      fontFamily: Global.mySemiboldFont),
                  hintText: "请输入数量",
                  border: InputBorder.none, // 去掉下滑线
                ),
              ),
            ),
          ),
          Row(
            children: [
              Spacer(),
              Text(
                "支付金额",
                style: TextStyle(
                  fontSize: 13,
                  color: Global.kTheme.textPrimary4,
                  fontFamily: Global.mySemiboldFont,
                ),
              ),
              SizedBox(
                width: 8,
              ),
              Text(
                (widget.type == 1 || widget.type == 3)
                    ? "¥${widget.goodsinfo!.info!.basePrice ?? ""}"
                    : "¥${widget.goodsinfo!.info!.price ?? ""}",
                style: TextStyle(
                    fontSize: 14,
                    color: Color(0xFFDc241C),
                    fontFamily: Global.myDINFont),
              ),
            ],
          ),
          SizedBox(
            height: 16,
          ),
        ],
      ),
    );
  }

  //支付方式
  Widget payView() {
    return Container(
      child: Column(
        children: [
          article?.value == "true"
              ? payItem(
                  icon: "icon_wx",
                  title: "微信",
                  describe: "选择微信支付",
                  isSelect: payType == 2,
                  name: 2)
              : SizedBox(),
          article?.value == "true"
              ? Container(
                  margin: EdgeInsets.only(left: 20),
                  color: Global.kTheme.colorLine,
                  height: 1,
                  width: double.infinity,
                )
              : SizedBox(),
          alArticle?.value == "true"
              ? payItem(
                  icon: "icon_zfb",
                  title: "支付宝",
                  describe: "选择支付宝支付",
                  isSelect: payType == 1,
                  name: 1)
              : SizedBox(),
        ],
      ),
    );
  }

  //item
  Widget payItem(
      {String? icon,
      String? title,
      String? describe,
      bool? isSelect,
      int? name}) {
    return InkWell(
      onTap: () {
        setState(() {
          payType = name!;
        });
      },
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 15, vertical: 14),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            LoadImage(
              icon!,
              width: 28,
              height: 28,
            ),
            SizedBox(
              width: 10,
            ),
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  title!,
                  style: TextStyle(
                      fontSize: 14,
                      color: Global.kTheme.textPrimary6,
                      fontFamily: Global.mySemiboldFont),
                ),
                Text(
                  describe!,
                  style: TextStyle(fontSize: 12, color: Color(0xFFA0A0A0)),
                ),
              ],
            ),
            Spacer(),
            Icon(
              (isSelect ?? false)
                  ? Icons.check_circle
                  : Icons.radio_button_unchecked_rounded,
              size: 18,
            ),
          ],
        ),
      ),
    );
  }

  //购买须知
  Widget instructionsView() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 15, vertical: 14),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            "购买须知",
            style: TextStyle(
              fontSize: 14,
              color: Global.kTheme.textPrimary1,
              fontFamily: Global.mySemiboldFont,
            ),
          ),
          SizedBox(
            height: 10,
          ),
          Text(
            "数字藏品为虚拟数字商品，而非实物，仅限经实名认证为年满14周岁的中国大陆用户购买。数字藏品的版权由发行方或原创者拥有，除另行取得版权拥有者书面同意外，用户不得将数字藏品用于任何商业用途。本商品一经售出，不支持退换。请勿对数字藏品进行炒作、场外交易、欺诈，或以任何其他非法方式进行使用",
            style: TextStyle(
                fontSize: 12,
                color: Global.kTheme.inputHint1,
                fontFamily: Global.mySemiboldFont),
          ),
        ],
      ),
    );
  }
  void toWebAipay(dynamic model) async{
    if(model["body"]!=null && model["body"]["pay_url"]!=null){
      var _url= model["body"]["pay_url"];
      if (!await launch(_url)) throw 'Could not launch $_url';
      EasyLoading.dismiss();

      await showDialog(
          context: context,
          builder: (context) {
            return Container(
              alignment: Alignment.center,
              padding: EdgeInsets.all(30),
              child: SizedBox(
                width: 200,
                height: 220,
                child: Container(
                  padding: EdgeInsets.all(30),
                  decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius:
                      BorderRadius.all(Radius.circular(10))),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Icon(Icons.offline_pin_rounded,size: 40,color: Colors.green,),
                      SizedBox(
                        height: 10,
                      ),
                      Text(
                        "支付完成",
                        style: TextStyle(
                          fontSize: 18,
                          color: Global.kTheme.textPrimary6,
                          fontFamily: Global.mySemiboldFont,
                        ),
                      ),

                      SizedBox(
                        height: 10,
                      ),

                      SizedBox(
                        height: 10,
                      ),
                      MyButton(
                          minHeight: 40,
                          text: "完成",
                          fontSize: 17,
                          textColor: Global.kTheme.textPrimary5,
                          backgroundColor:
                          Global.kTheme.colorPrimary,
                          onPressed: () {
                            if (widget.type == 1) {
                              Get.to(SplitBoxPage(
                                  goodid: mangModel.goodsId ?? "",
                                  id: widget.goodsinfo!.info!.id.toString()));
                            } else {
                              Navigator.of(Get.context!)
                                ..pop()
                                ..pop()
                                ..pop();
                            }
                          })
                    ],
                  ),
                ),
              ),
            );
          });
    }
  }
  void toAlipay(SpecialCastModel model) async {
    print("支付中----");
    //检测是否安装支付宝
    var result = await tobias.isAliPayInstalled();

    if (!result) {
      return EasyLoading.showToast('请安装支付宝');
    }

    if (result) {
      //去支付
      //orderInfo为后台返回的orderInfo
      var payResult = await tobias.aliPay(model.body ?? "");

      if (payResult['result'] != null) {
        if (payResult['resultStatus'].toString() == "9000") {
          EasyLoading.showToast('支付成功');
          if (widget.type == 1) {
            Get.to(SplitBoxPage(
                goodid: mangModel.goodsId ?? "",
                id: widget.goodsinfo!.info!.id.toString()));
          } else {
            Navigator.of(Get.context!)
              ..pop()
              ..pop();
          }
        } else {
          EasyLoading.showToast('支付失败');
        }
      }
    }
  }

  void toWXPay(dynamic model) async {
    print("支付中----");
    await fluwx.registerWxApi(
        appId: "wx0f7153ca682343e0",
        universalLink: "https://www.com.example.limaiwl/app/");

    var result = await fluwx.isWeChatInstalled;
    if (!result) {
      return EasyLoading.showToast('请安装微信');
    }

    if (result) {
      //去支付
      //orderInfo为后台返回的orderInfo
      // 将下面这些参数替换成后台返回的即可
      var payRes = await fluwx.payWithWeChat(
        appId: model["body"]["appid"],
        partnerId: model["body"]["partnerid"],
        prepayId: model["body"]["prepayid"],
        packageValue: model["body"]["package"],
        nonceStr: model["body"]["noncestr"],
        timeStamp: model["body"]["timestamp"],
        sign: model["body"]["sign"],
      );

      // 支付回调
      // 一般情况下打开微信支付闪退，errCode为 -1 ，多半是包名、签名和在微信开放平台创建时的配置不一致。
      // 监听支付结果
      if (testSubscription != null) {
        testSubscription?.cancel();
      }
      testSubscription = fluwx.weChatResponseEventHandler.listen((event) async {
        print(event.errCode);
        // 支付成功
        if (event.errCode == 0) {
          EasyLoading.showToast('支付成功');
          if (widget.type == 1) {
            Get.to(SplitBoxPage(
                goodid: mangModel.goodsId ?? "",
                id: widget.goodsinfo!.info!.id.toString()));
          } else {
            Navigator.of(Get.context!)
              ..pop()
              ..pop();
          }
        } else {
          // 关闭弹窗
          EasyLoading.showToast('支付失败');
        }
      });
    }
  }

  String omitAddress(String address, {int len = 4}) {
    if (address == null || address.isEmpty) return "";
    if (address.length > (len * 2)) {
      return address.substring(0, len) +
          '...' +
          address.substring(address.length - len, address.length);
    }
    return address;
  }

  void getConfigNameDetail(String name) async {
    try {
      List list = await ServiceRepository.getConfigNameDetail(name);
      list.forEach((element) {
        if (element.name.toString().trim() == name) {
          article = element;
          if (article?.value == "false" && payType == 2) {
            payType = -1;
          }
        }
      });
    } catch (e, s) {}
    setState(() {});
  }

  void getConfigNameDetailAli(String name) async {
    try {
      List list = await ServiceRepository.getConfigNameDetail(name);
      list.forEach((element) {
        if (element.name.toString().trim() == name) {
          alArticle = element;
          if (alArticle?.value == "true") {
            payType = 1;
          } else {
            payType = 2;
          }
        }
      });
      getConfigNameDetail("wechatpay_is_open");
    } catch (e, s) {}
    setState(() {});
  }
}
